package Thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//实现一个固定线程数量的线程池
class MyThreadPool{
    //任务队列
    private BlockingQueue<Runnable> queue=null;
    public MyThreadPool(int n){
        //创建容量为1000的任务队列
        queue=new LinkedBlockingQueue<Runnable>(1000);
        //创建n个线程
        for (int i=0;i<n;i++){
            Thread thread=new Thread(()->{
                try {
                    while(true){
                        Runnable task=queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
        }
    }
    //将任务放到队列里
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }
}
public class Demo35 {
    public static void main(String[] args) throws InterruptedException {
    MyThreadPool myThreadPool=new MyThreadPool(5);
    for(int i=0;i<50;i++){
        int id=i;
        myThreadPool.submit(()->{
            System.out.println(Thread.currentThread().getName()+" "+id);
        });
    }
    }
}
